//微信小程序支付封装,暂支持md5加密，不支持sha1
/**
 ***create order by jianchep 2016/11/22
 **/
var config = require('../configs/db_config.js')
var xml2js = require('xml2js');
var request = require("request")
var crypto = require('crypto')
let data = require('../libs/data');
var key = config.key
var builder = new xml2js.Builder();  // JSON->xml
var parser = new xml2js.Parser();   //xml -> json




// 获取prepay_id
function getXMLNodeValue(node_name, xml) {
    console.log('xml---',xml);
    var tmp = xml.split("<" + node_name + ">")
    var _tmp = tmp[1].split("</" + node_name + ">")
    return _tmp[0]
}
// object-->string
function raw(args) {
    var keys = Object.keys(args)
    keys = keys.sort()
    var newArgs = {}
    keys.forEach(function(key) {
        newArgs[key] = args[key]
    })
    var string = ''
    for (var k in newArgs) {
        string += '&' + k + '=' + newArgs[k]
    }
    string = string.substr(1)
    return string
}
// 随机字符串产生函数
function createNonceStr() {
    return Math.random().toString(36).substr(2, 15)
}
// 时间戳产生函数
function createTimeStamp() {
    return parseInt(new Date().getTime() / 1000) + ''
}
// 支付md5加密获取sign
function paysignjs(appid, nonceStr, package, signType, timeStamp) {
    var ret = {
        appId: appid,
        nonceStr: nonceStr,
        package: package,
        signType: signType,
        timeStamp: timeStamp
    }
    var string = raw(ret)
    string = string + '&key=' + key
    var sign = crypto.createHash('md5').update(string, 'utf8').digest('hex')
    return sign.toUpperCase()
}
// 统一下单接口加密获取sign
function paysignjsapi(appid, attach, body,detail, mch_id, nonce_str, notify_url, openid, out_trade_no, spbill_create_ip, total_fee, trade_type) {
    var ret = {
        appid: appid,
        attach: attach,
        body: body,
        detail: detail,
        mch_id: mch_id,
        nonce_str: nonce_str,
        notify_url: notify_url,
        openid: openid,
        out_trade_no: out_trade_no,
        spbill_create_ip: spbill_create_ip,
        total_fee: total_fee,
        trade_type: trade_type
    }
    var string = raw(ret)
    string = string + '&key=' + key
    console.log('string---------',string);
    var crypto = require('crypto')
    var sign = crypto.createHash('md5').update(string, 'utf8').digest('hex')
    console.log('sign--',sign);
    return sign.toUpperCase()
}











module.exports = {
    // 下单接口
    order: function(req, res) {

        var orderId = req.body.orderId;
        var mch_id = req.body.mch_id;
        var openid = req.body.openid;
        var total_fee = req.body.total_fee;
        var notify_url = 'https://api.jiyouhome.com/shopc/pay/weChat/back.json';
        var appid = config.appId
        var nonce_str = createNonceStr()
        var timeStamp = createTimeStamp()
        var url = "https://api.mch.weixin.qq.com/pay/unifiedorder"
        var formData = "<xml>"
        formData += "<appid>" + appid + "</appid>" //appid  
        formData += "<attach>" + orderId + "</attach>" //附加数据
        formData += "<body>" + orderId + "</body>"
        formData += "<mch_id>" + mch_id + "</mch_id>" //商户号  
        formData += "<nonce_str>" + nonce_str + "</nonce_str>" //随机字符串，不长于32位。  
        formData += "<notify_url>" + notify_url + "</notify_url>"
        formData += "<detail>" + orderId + "</detail>"
        formData += "<openid>" + openid + "</openid>"
        formData += "<out_trade_no>" + orderId + "</out_trade_no>"
        formData += "<spbill_create_ip>127.0.0.1</spbill_create_ip>"
        formData += "<total_fee>" + total_fee + "</total_fee>"
        formData += "<trade_type>JSAPI</trade_type>"
        formData += "<sign>" + paysignjsapi(appid, orderId, orderId,orderId, mch_id, nonce_str, notify_url, openid, orderId, '127.0.0.1', total_fee, 'JSAPI') + "</sign>"
        formData += "</xml>"
        console.log('formData---',formData);
        var self = this
        request({
            url: url,
            method: 'POST',
            headers: {
                "Content-Type": "application/json;charset=utf-8",
            },
            body: formData
            }, function(err, response, body) {
            if (!err && response.statusCode == 200) {
                parser.parseString(body.toString("utf-8"), function (err, result) {
                    var resultData = result.xml;
                    console.log('结果：',resultData);
                    if(resultData.return_code[0]!='FAIL'){
                        data.code = '200';
                        data.msg = '获取成功';

                        //签名
                        var _paySignjs = paysignjs(appid, nonce_str, 'prepay_id=' + resultData.prepay_id[0], 'MD5', timeStamp)
                        var args = {
                            appId: appid,
                            timeStamp: timeStamp,
                            nonceStr: nonce_str,
                            signType: "MD5",
                            package: 'prepay_id='+resultData.prepay_id[0],
                            paySign: _paySignjs
                        }

                        data.data = args;
                    }else{
                        data.code = '101';
                        data.msg = '获取失败';
                        data.data = resultData.return_msg[0];
                    }


                });
                res.status(200).send(JSON.stringify(data));
            } else {
                console.log(body)
            }
        })
    },
    getOpendId: function (req, res) {
        console.log('req: ',req);
        var code  = req.body.code;
        var body = {
            "code": code,
        };
        request({
            url: 'https://api.weixin.qq.com/sns/jscode2session?appid=wx1d6e956bc2775a9f&secret=98a1fac2112605018497daaa86b1da90&js_code='+code+'&grant_type=authorization_code',
            method: "POST",
            headers: {
                "Content-Type": "application/json;charset=utf-8",
            },
            body: JSON.stringify(body)
        }, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                console.log(response.body);
                data.code = '200';
                data.msg = '获取成功';
                data.data = JSON.parse(response.body).openid;
            } else {
                data.code = '101';
                data.msg = '获取失败';
                data.data = '';
            }
            res.status(200).send(JSON.stringify(data));
        });
    }
}